//
//  ANFeedbackController.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/6/11.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANFeedbackController.h"
#import "FeedbackShopNameView.h"
#import "FeedbackInputView.h"
#import "HDragItemListView.h"
#import <CTAssetsPickerController.h>
#import <YBImageBrowser/YBImageBrowser.h>
#import "MineInfoFooterView.h"
#import "ANFeedbackRecordController.h"

@interface ANFeedbackController ()<CTAssetsPickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,YBImageBrowserDataSource>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) FeedbackShopNameView *shopNameView;
@property (nonatomic, strong) FeedbackInputView *inputView;
@property (nonatomic, strong) HDragItemListView *listView;
@property (nonatomic, strong) MineInfoFooterView *footer;

@end

@implementation ANFeedbackController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"意见反馈";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"历史反馈" style:UIBarButtonItemStyleDone target:self action:@selector(feedbackRecordAction)];
}

- (void)setupSubViews
{
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.alwaysBounceVertical = YES;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.shopNameView = [[FeedbackShopNameView alloc] init];
    [self.scrollView addSubview:self.shopNameView];
    [self.shopNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollView).offset(15);
        make.right.equalTo(self.scrollView).offset(-15);
        make.top.equalTo(self.scrollView).offset(10);
        make.height.equalTo(@48);
        make.width.equalTo(@(kScreenW-30));
    }];
    
    self.inputView = [[FeedbackInputView alloc] init];
    [self.scrollView addSubview:self.inputView];
    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.shopNameView);
        make.top.equalTo(self.shopNameView.mas_bottom).offset(10);
        make.height.equalTo(@145);
    }];
    
    UILabel *maxLimitLab = [[UILabel alloc] init];
    maxLimitLab.text = @"添加图片说明";
    maxLimitLab.textColor = kColor333333;
    maxLimitLab.font = [UIFont systemFontOfSize:14];
    [self.scrollView addSubview:maxLimitLab];
    [maxLimitLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.shopNameView);
        make.top.equalTo(self.inputView.mas_bottom).offset(18);
    }];
    
    HDragItem *item = [[HDragItem alloc] init];
    item.backgroundColor = [UIColor whiteColor];
    item.image = [UIImage imageNamed:@"photo_add"];
    item.isAdd = YES;
    self.listView = [[HDragItemListView alloc] initWithFrame:CGRectMake(0, 0, kScreenW - 10, 0)];
    self.listView.maxItem = 3;
    
    // 设置排序时，缩放比例
    self.listView.scaleItemInSort = 1.3;
    // 需要排序
    self.listView.isSort = YES;
    self.listView.isFitItemListH = YES;
    
    [self.listView addItem:item];
    
    WeakSelf
    [self.listView setClickItemBlock:^(HDragItem *item) {
        if (item.isAdd) {
            [weakSelf addPhoto];
        }
        else {
            [weakSelf browserImage:item];
        }
    }];
    
    /**
     * 移除tag 高度变化，得重设
     */
    self.listView.deleteItemBlock = ^(HDragItem *item) {
        HDragItem *lastItem = [weakSelf.listView.itemArray lastObject];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!lastItem.isAdd) {
                HDragItem *item = [[HDragItem alloc] init];
                item.backgroundColor = [UIColor whiteColor];
                item.image = [UIImage imageNamed:@"photo_add"];
                item.isAdd = YES;
                [weakSelf.listView addItem:item];
            }
            [weakSelf.listView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.equalTo(@(weakSelf.listView.itemListH));
            }];
        });
    };
    
    [self.scrollView addSubview:self.listView];
    
    [self.listView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(maxLimitLab.mas_bottom).offset(15);
        make.left.equalTo(self.scrollView).offset(5);
        make.right.equalTo(self.scrollView).offset(-5);
        make.height.equalTo(@(self.listView.itemListH));
    }];
    
    self.footer = [[MineInfoFooterView alloc] init];
    self.footer.title = @"确认提交";
    [self.scrollView addSubview:self.footer];
    [self.footer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.scrollView);
        make.top.equalTo(self.listView.mas_bottom).offset(50);
        make.bottom.equalTo(self.scrollView).offset(-20);
        make.height.equalTo(@(kWidth(58)));
    }];
    // 反馈上传
    self.footer.sureHandler = ^{
        [weakSelf postFeedback];
    };
}

- (void)feedbackRecordAction
{
    ANFeedbackRecordController *vc = [[ANFeedbackRecordController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)addPhoto
{
    LLAlertViewController *vc = [[LLAlertViewController alloc] init];
    vc.actions = @[@"拍摄",@"从手机相册中选择"];
    vc.actionBlock = ^(NSInteger index, NSString *actionTitle) {
        if (index == 1) {
            [self takeAlbum];
        }else if (index == 0) {
            [self takePhoto];
        }
    };
    [vc presentBottomViewControllerFromController:self];
}

// 图片预览
- (void)browserImage:(HDragItem *)item
{
    YBImageBrowser *browser = [YBImageBrowser new];
    browser.dataSource = self;
    browser.currentIndex = [self.listView.itemArray indexOfObject:item];
    [browser show];
}

// 打开相册
- (void)takeAlbum
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
        
        picker.showsSelectionIndex = YES;
        
        picker.delegate = self;
        
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            picker.modalPresentationStyle = UIModalPresentationFormSheet;
        }
        
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        [window.rootViewController presentViewController:picker animated:YES completion:nil];
    });
}

// 打开相机
- (void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable:sourceType]) {
        
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = false;
        picker.sourceType = sourceType;
        picker.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        NSLog(@"请在真机中使用");
    }
}

// 将选择的资源图片数组转成UIImage数组
- (NSArray<UIImage *> *)prepare
{
    NSMutableArray *images = @[].mutableCopy;
    for (HDragItem *item in self.listView.itemArray) {
        if (!item.isAdd) {
            
            [images addObject:item.image];
            
        }
    }
    return images;
}

#pragma mark - YBImageBrowserDataSource
- (NSUInteger)yb_numberOfCellForImageBrowserView:(YBImageBrowserView *)imageBrowserView {
    return [self prepare].count;
}
- (id<YBImageBrowserCellDataProtocol>)yb_imageBrowserView:(YBImageBrowserView *)imageBrowserView dataForCellAtIndex:(NSUInteger)index {
    YBImageBrowseCellData *data = [YBImageBrowseCellData new];
    NSArray *imgs = [self prepare];
    data.imageBlock = ^__kindof UIImage * _Nullable{
        return imgs[index];
    };
    data.sourceObject = self.listView.itemArray[index];
    return data;
}

#pragma mark - CTAssetsPickerControllerDelegate
//从相册选取图片后会调用该代理
-(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    if (asset.mediaType != PHAssetMediaTypeImage)
    {
        [MBProgressHUD showMessage:@"只能上传照片"];
        return NO;
    }
    NSArray *imgs = [self prepare];
    if (imgs.count + picker.selectedAssets.count >= 3) {
        [MBProgressHUD showMessage:[NSString stringWithFormat:@"最多上传三张图片\n(已选择%ld张，还可选择%lu张)",imgs.count,(unsigned long)picker.selectedAssets.count]];
        return NO;
    }
    return YES;
}

// 在相册中选择图片后调用此代理
- (void)assetsPickerController:(CTAssetsPickerController *)picker didSelectAsset:(PHAsset *)asset
{
    
}

// 在相册中取消选择图片后调用此代理
- (void)assetsPickerController:(CTAssetsPickerController *)picker didDeselectAsset:(PHAsset *)asset
{
    
}

- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets {
    //关闭相册界面
    [picker dismissViewControllerAnimated:YES completion:^{
        
        dispatch_group_t group = dispatch_group_create();
        dispatch_queue_t queue = dispatch_get_main_queue();
        NSMutableArray *items = @[].mutableCopy;
        for (int i = 0; i < assets.count; i++) {
            PHAsset *asset = assets[i];
            CGFloat scale = [UIScreen mainScreen].scale;
            PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
            options.synchronous = YES;
            options.resizeMode = PHImageRequestOptionsResizeModeNone;
            CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
            dispatch_group_enter(group);
            dispatch_async(queue, ^{
                [[PHImageManager defaultManager] requestImageForAsset:asset
                                                           targetSize:size
                                                          contentMode:PHImageContentModeDefault
                                                              options:options
                                                        resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                            UIImage *img = result;
                                                            NSData *bigData = UIImagePNGRepresentation(result);
                                                            if (bigData.length > 500 * 1024) {
                                                                NSData *data = UIImageJPEGRepresentation(result, 400*1024.0/bigData.length);
                                                                img = [UIImage imageWithData:data];
                                                            }
                                                            
                                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                                HDragItem *item = [[HDragItem alloc] init];
                                                                item.isAdd = NO;
                                                                item.image = img;
                                                                item.backgroundColor = [UIColor purpleColor];
                                                                [items addObject:item];
                                                                WeakSelf
                                                                item.deletePhotoBlock = ^(HDragItem *item) {
                                                                    [weakSelf.listView deleteItem:item];
                                                                };
                                                            });
                                                            dispatch_group_leave(group);
                                                        }];
                
            });
        }
        dispatch_group_notify(group, queue, ^{
            [self.listView addItems:items];
            [self.listView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.equalTo(@(self.listView.itemListH));
            }];
        });
        
    }];
    
}

#pragma mark - UINavigationControllerDelegate,UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //关闭相机界面
    UIImage *img = nil;
    if ([picker allowsEditing]) {
        img = [info objectForKey:UIImagePickerControllerEditedImage];
    }
    else {
        img = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    NSData *bigData = UIImagePNGRepresentation(img);
    if (bigData.length > 400 * 1024) {
        NSData *data = UIImageJPEGRepresentation(img, 500*1024.0/bigData.length);
        img = [UIImage imageWithData:data];
    }
    HDragItem *item = [[HDragItem alloc] init];
    item.isAdd = NO;
    item.image = img;
    WeakSelf
    item.backgroundColor = [UIColor purpleColor];
    item.deletePhotoBlock = ^(HDragItem *item) {
        [weakSelf.listView deleteItem:item];
    };
    [self.listView addItem:item];
    [self.listView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(self.listView.itemListH));
    }];
    [picker dismissViewControllerAnimated:false completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)postFeedback
{
    if (!self.shopNameView.name || self.shopNameView.name.length == 0) {
        [MBProgressHUD showWarning:@"请输入商户名称"];
        return;
    }
    if (!self.inputView.text || self.inputView.text.length == 0) {
        [MBProgressHUD showWarning:@"请输入意见反馈"];
        return;
    }
    NSDictionary *post = @{
                           @"consumerName":self.shopNameView.name,
                           @"content":self.inputView.text
                           };
    NSDictionary *body = @{@"post":post.yy_modelToJSONString};
    [MBProgressHUD showActivityMessage:@"正在上传中..."];
    [URLManager.shareManager uploadUrlStr:Api_Post_Feedback images:[self prepare] parameters:body fileDataName:@"files" success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObj) {
        [MBProgressHUD hideHUD];
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
//                [MBProgressHUD showSuccess:@"反馈成功！"];
                [ANAlertManager alertSimpleMessage:@"感谢您的反馈，我们会尽快回复您！" handler:^(UIAlertAction * _Nonnull action) {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            }
            else {
                [MBProgressHUD showError:responseObj[@"message"]];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        
    }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
